package com.project.cheat;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class SocketServers extends JFrame {
  private JTextArea textArea;
  private JTextField input;
  private JButton jb1;
  private JButton jb2;
  private JButton jb3;
  private JButton jb4;
  private JButton jb5;
  public int port = 8888;
  private ServerSocket server;
  private ArrayList<user> users = new ArrayList<>();

  // 引擎只 连接 读 和 转发 消息
  public void NetEngine() throws IOException {
    while (true) {
      Socket socket = server.accept();
      ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
      ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
      try {
        // 耳朵
        while (true) {
          // 读
          Request request = (Request) in.readObject();
          if (request.isIslogin()) {
            for (user u : users) {
              if (request.getPwd().equals(u.getPassword())
                  && request.getFrom().equals(u.getAccount())) {
                u.setOut(out);
                u.setIslogin(true);
                out.writeObject(new Response("登陆成功，欢迎回来：" + request.getFrom() + "\n", true));
              } else {
                out.writeObject(new Response("登录失败，请校验用户名和密码...\n"));
              }
            }
          } else {
            out.writeObject(new Response(request.getFrom() + "说：" + request.getMsg()));
            textArea.append(request.getFrom() + "说：" + request.getMsg() + "\n");
          }

          //          textArea.append(request.getFrom() + "说:" + request.getMsg() + "\n");
          //          Maps.outMap.put(request.getFrom(), out);
          // 群发
          //          Maps.outMap
          //              .values()
          //              .forEach(
          //                  o -> {
          //                    try {
          //                      o.writeObject(new Response("这是转发的消息:" + request.getMsg() + "\n"));
          //                    } catch (IOException e) {
          //                      e.printStackTrace();
          //                    }
          //                  });
        }
      } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
      }
    }
  }

  public static void checkaccount(String username, String pwd) {}

  public void send(Response response) throws IOException {
    for (user u : users) {
      u.getOut().writeObject(response);
    }
    textArea.append("服务器说：" + response.getMsg() + "\n");
  }

  public void stopNetEngine() throws IOException {
    this.jb2.setEnabled(true);
    this.jb3.setEnabled(false);
    this.textArea.append("服务器已关闭... \n");
    this.server.close();
  }

  public void startEngin() {
    try {
      this.server = new ServerSocket(port);
      users.add(new user("root", "123456"));
      NetEngine();

    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public SocketServers() throws HeadlessException {
    this.setTitle("❤网络姻缘一线牵❤ (服务端)");
    this.jb1 = new JButton("设置端口");
    jb1.setBounds(40, 20, 100, 50);
    this.jb2 = new JButton("启动服务");
    jb2.setBounds(180, 20, 100, 50);
    this.jb3 = new JButton("停止服务");
    jb3.setEnabled(false);
    jb3.setBounds(320, 20, 100, 50);
    this.jb4 = new JButton("退出");
    jb4.setBounds(460, 20, 100, 50);
    this.textArea = new JTextArea();
    textArea.setLineWrap(true);
    textArea.setEditable(false);
    textArea.setBounds(50, 80, 500, 300);
    this.input = new JTextField();
    input.setBounds(50, 400, 400, 30);
    this.jb5 = new JButton("发送");
    jb5.setBounds(450, 400, 110, 30);
    JScrollPane scroll = new JScrollPane();
    this.add(jb1);
    this.add(jb2);
    this.add(jb3);
    this.add(jb4);
    this.add(jb5);
    //    scroll.setViewportView(textArea);
    this.add(textArea);

    this.add(input);
    this.setBounds(420, 250, 600, 500);
    this.setLayout(null);
    this.setResizable(false);
    this.setVisible(true);
    this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    jb1.addActionListener(
        e -> {
          JFrame jf = new JFrame("监听端口设置");
          jf.setLayout(null);
          jf.setBounds(570, 420, 300, 200);
          JLabel text = new JLabel("端口号:");
          text.setBounds(50, 30, 50, 30);
          JTextField port = new JTextField("" + SocketServers.this.port);
          port.setBounds(140, 30, 80, 30);
          JLabel text2 = new JLabel("默认端口为 : 8888");
          text2.setBounds(95, 70, 200, 40);
          JButton jb = new JButton("确定");
          jb.setBounds(220, 90, 80, 30);
          jf.add(text);
          jf.add(port);
          jf.add(text2);
          jf.add(jb);
          jf.setVisible(true);
          jf.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
          jb.addActionListener(
              e1 -> {
                SocketServers.this.port = Integer.parseInt(port.getText());
                jf.dispose();
              });
        });
    jb2.addActionListener(
        e2 -> {
          this.jb2.setEnabled(false);
          this.jb3.setEnabled(true);
          this.textArea.append("服务器已在" + this.port + "启动... \n");
          new Thread(this::startEngin).start();
        });

    jb3.addActionListener(
        e3 -> {
          try {
            SocketServers.this.stopNetEngine();
          } catch (IOException e) {
            e.printStackTrace();
          }
        });
    jb4.addActionListener(e4 -> this.dispose());

    jb5.addActionListener(
        e5 -> {
          String msg = input.getText();
          try {
            send(new Response(msg));
          } catch (IOException e) {
            e.printStackTrace();
          }
          input.setText("");
        });
  }

  public static void main(String[] args) {
    new SocketServers();
    //    new ClientServers();
  }
}
